import Vue from 'vue'
import Vuex from 'vuex'

//1。安装插件
Vue.use(Vuex)

//2.创建store对象
const store = new Vuex.Store({
    state: {
        cartList: []
    },
    mutations: {
        addCounter(state, payload) {
            console.log(state);
            payload.count++
        },
        addToCart(state, pauload) {
            state.cartList.push(pauload)
        }

    },
    actions: {
        //mutations唯一的目的就是修改state中的状态
        //mutations中的每一个方法尽可能完成的事件比较单一
        addCart(context, payload) {

            //1.查找之前数组中是否有该商品

            let oldProduct = context.state.cartList.find(item => item.iid === payload.iid)

            if (oldProduct) {

                // oldProduct.count += 1
                context.commit('addCounter', oldProduct)
            } else {
                payload.count = 1
                context.commit('addToCart', payload)

            }

        }
    }
})

//3.挂载vue实列
export default store